package com.qq.BFMRSE.index;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

import com.qq.BFMRSE.entity.BloomFilter;
import com.qq.BFMRSE.entity.indexTreeNode;
import com.qq.BFMRSE.extractWord.wordTFAndIDFInfo;

import net.sf.json.JSONArray;


public class buildIndexTreeHelper {

	public static Queue<indexTreeNode> getallLeafIndexTree(List<String> fidList)
	{
		Queue<indexTreeNode> resultQueue=new LinkedBlockingQueue<indexTreeNode>();
		Iterator<String> iterator=fidList.iterator();
		while(iterator.hasNext())
		{
			String fid=iterator.next();
			indexTreeNode tempIndexNode=getNewLeafIndexTree(fid);
			resultQueue.add(tempIndexNode);
		}
		return resultQueue;
	}

	public static indexTreeNode getNewLeafIndexTree(String fid)
	{
		indexTreeNode resultNode=new indexTreeNode();
		Set<String> wordList=wordTFAndIDFInfo.getWordAndIdfsByFileName(fid).keySet();
	    Iterator<String>iterator=wordList.iterator();
	    BloomFilter bf=new BloomFilter();
	    while (iterator.hasNext()) {
			String tempWord=iterator.next();
			bf.addValue(tempWord);
		}
	    resultNode.setBf(bf);
	    resultNode.setFID(fid);
		return resultNode;
	}
	public static List<indexTreeNode> getAllBuildTreeNode(indexTreeNode root)
	{
		List<indexTreeNode> resultList=new ArrayList<indexTreeNode>();
		Queue<indexTreeNode> queue=new LinkedBlockingQueue<indexTreeNode>();//���ڹ�����ȱ�����ʱʹ��
		indexTreeNode currNode=root;
		if(currNode!=null)
		{
			queue.add(currNode);
		}
		while(!queue.isEmpty())
		{
			indexTreeNode tempNode=queue.peek();
			resultList.add(tempNode);
			if(tempNode.getLeft()!=null)
			{
				queue.add(tempNode.getLeft());
			}
			if(tempNode.getRight()!=null)
			{
				queue.add(tempNode.getRight());
			}
			
		}
		return resultList;
		
	}
	public static void updateIndexTree(indexTreeNode node)
	{
		indexTreeNode currNode=node;
		indexTreeNode parentNode=new indexTreeNode();
		indexTreeNode otherNode=new indexTreeNode();
		while(currNode.getParent()!=null)
		{
			parentNode=currNode.getParent();
			if(parentNode.getRight()==currNode)
			{
				otherNode=parentNode.getLeft();
			}
			else {
				otherNode=parentNode.getRight();
			}
			BloomFilter tempBf=getNewBloomFilter(currNode.getBf(),otherNode.getBf());
			parentNode.setBf(tempBf);
			currNode=parentNode;
		}
	}
	
	public static BloomFilter getNewBloomFilter(BloomFilter bf1,BloomFilter bf2)
	{
		BloomFilter resultBf=new BloomFilter();
		BitSet tempBitSet=new BitSet();
		int length=bf1.BitsLength();
		for(int i=0;i<length;i++)
		{
			if(bf1.getBits().get(i)==true||bf2.getBits().get(i)==true)
			{
				tempBitSet.set(i, true);
			}
			else {
				tempBitSet.set(i, false);
			}
		}
		resultBf.setBits(tempBitSet);
		return resultBf;
	}
	
}
